from mcp.server.auth.provider import TokenVerifier, AccessToken
import httpx
# import re  # 不支持异步
from loguru import logger

class IntrospectionTokenVerifier(TokenVerifier):
    def __init__(self, introspect_endpoint: str):
        self.introspect_endpoint = introspect_endpoint

    async def verify_token(self, token: str) -> AccessToken | None:
        # 来校验用户提交上来的token
        timeout = httpx.Timeout(5.0, connect=10.0) # 连接超时时间为 10 秒。其他操作超时时间为 5 秒。
        limits = httpx.Limits(max_connections=10, max_keepalive_connections=5) # 最大连接量是10，最大活跃连接数是5
        async with httpx.AsyncClient(
                timeout=timeout,
                limits=limits,
        ) as client:
            response = await client.post(
                self.introspect_endpoint,
                data={"token": token},
                headers={"Content-Type": "application/x-www-form-urlencoded"}, # 表单内容是这么写
                # 如果introspect_handler是通过request.json(),那么这里就是json={"token": token},然后内容就是application/json
            )
            if response.status_code != 200:
                logger.info(f"Token请求失败！状态码为：{response.status_code}")
                return None

            data = response.json()
            if not data.get("active", False): # 如果active不是True
                return None

            return AccessToken(
                token=token,
                client_id=data.get("client_id"),
                scopes=data.get("scope", "").split(" "),
                expires_at=data.get("exp"),
                resource=data.get("aud"),
            )
